import { createRouter, createWebHistory } from 'vue-router'
import ChatView from '@/views/chat/chatView.vue'
import LoginView from '@/views/login/login.vue'
import ArticleHall from '@/views/community/ArticleHall.vue'
import ArticleDetail from '@/views/community/ArticleDetail.vue'
import PublishArticle from '@/views/community/PublishArticle.vue'
import UserProfile from '@/views/community/UserProfile.vue'
import CollaborativePlan from '@/views/collaboration/CollaborativePlan.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/chat',
    name: 'Chat',
    component: ChatView,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginView
  },
  {
    path: '/community/articles',
    name: 'ArticleHall',
    component: ArticleHall,
    meta: { requiresAuth: true }
  },
  {
    path: '/community/articles/:id',
    name: 'ArticleDetail',
    component: ArticleDetail,
    meta: { requiresAuth: true }
  },
  {
    path: '/community/publish',
    name: 'PublishArticle',
    component: PublishArticle,
    meta: { requiresAuth: true }
  },
  {
    path: '/community/profile/:userId?',
    name: 'UserProfile',
    component: UserProfile,
    meta: { requiresAuth: true }
  },
  {
    path: '/collaboration/plan/:planId?',
    name: 'CollaborativePlan',
    component: CollaborativePlan,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫：检查用户是否登录
router.beforeEach((to, from, next) => {
  const isLoggedIn = !!localStorage.getItem('token')


  // 如果路由需要登录，但用户未登录，重定向到登录页
  if (to.meta.requiresAuth && !isLoggedIn) {
    next('/login')
  }
  // 如果用户已登录，访问登录页时重定向到聊天页
  else if (to.path === '/login' && isLoggedIn) {
    next('/ArticleHall')
  }
  else {
    console.log('允许访问');
    next()
  }
})

export default router
